//
//  AVFoundation+Image.swift
//  SwiftCode
//
//  Created by yuhus on 2023/9/21.
//  https://developer.apple.com/documentation/avfoundation/media_reading_and_writing/creating_images_from_a_video_asset

import Foundation
import AVFoundation
import UIKit

extension AVFoundationExample {
  /// AVFoundation 使用 AVAssetImageGenerator 可以轻松地从应用程序的视频内容生成图像。
  func generateImage() {
    guard let url : URL = URL(string: self.urls[0]) else { return }
    
    let asset = AVAsset(url: url)
    let generator = AVAssetImageGenerator(asset: asset)
    // 生成相当于 340 像素宽的图像。
    generator.maximumSize = CGSize(width: 340, height: 0)
    
    // 要允许在不早于您请求的时间且不晚于请求时间后两秒的时间范围内生成图像，请按如下所示设置其容差值。
    // Configure the generator's time tolerance values.
    generator.requestedTimeToleranceBefore = .zero
    generator.requestedTimeToleranceAfter = CMTime(seconds: 2, preferredTimescale: 600)
    
    // Generate an image at time zero.
    DispatchQueue.global().async {
      let time = CMTime(seconds: 6, preferredTimescale: 600)
      if let cgImage = try? generator.copyCGImage(at: time, actualTime: nil) {
        DispatchQueue.main.async { [weak self] in
          self?.displayImage(cgImage)
        }
      }
    }
  }
  
  private func displayImage(_ cgImage: CGImage) {
    let image = UIImage(cgImage: cgImage)
    let controller = ImageViewController()
    controller.imageView.image = image
    navigationController?.pushViewController(controller, animated: true)
  }
}
